/*
 * Copyright (C) 2010-2011 Comcast Cable.  All Rights Reserved.
 */
package com.hercules.android.receiver.connection.parser.json.itemparsers;

import com.google.gjson.JSONObject;
import com.hercules.android.receiver.connection.parser.CommandParsingException;

/**
 * Parser that is dependent on some property of parent object.
 * <p>
 * AndroidAssembly2 this class was added in Android Assembly 2
 *
 * @author 7realm
 * @version 1.0
 */
public abstract class DependentParser extends FieldParser {
    /** Represents name of dependent property. */
    private final String dependent;

    /**
     * Constructor for {@link DependentParser}.
     *
     * @param required if property is required
     * @param dependent the name of dependent property
     */
    public DependentParser(boolean required, String dependent) {
        super(required);
        this.dependent = dependent;
    }

    /**
     * Parses dependent property. Add value of dependent property to path.
     *
     * @param path the path to value
     * @param json the JSON
     * @param keyName the name of current JSON key
     * @param instance the instance of object, parsed value will be set to it
     * @return the parsed value
     * @throws CommandParsingException if error occurs while parsing
     */
    @Override
    protected Object doParse(StringBuilder path, JSONObject json, String keyName, Object instance)
        throws CommandParsingException {
        // add dependent property to path if this is needed
        if (dependent != null) {
            String dependentValue =
                getStringValue(json, dependent, "JSON does not have required dependent property '" + dependent
                    + "', item types of the JSON onject cannot be determined.");

            // add dependent property name to path
            if (path.length() > 0) {
            	path.append('.');
            }
            path.append(dependentValue);
        }
        return null;
    }
}
